package com.kuaiyin.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.util.UUID;

/**
 * 阿里云OSS操作工具类
 */
@Slf4j
public class AliyunOSSUtils {

    /**
     * 上传文件
     *
     * @param endpoint   endpoint域名
     * @param bucketName 存储空间的名字
     * @param content    内容字节数组
     * @extName extName 文件后缀名
     */
    public static String upload(String endpoint, String bucketName, byte[] content, String extName) throws Exception {
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = UUID.randomUUID() + extName;
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = endpoint.replaceAll(".*oss-(.+?)\\..*", "$1");

        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content));
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            log.error("捕获到 OSSException，这意味着您的请求已经发送到了 OSS，但因某种原因被拒绝了。");
            log.error("错误信息: {}", oe.getErrorMessage());
            log.error("错误代码: {}", oe.getErrorCode());
            log.error("请求 ID: {}", oe.getRequestId());
            log.error("主机 ID: {}", oe.getHostId());
        } catch (ClientException ce) {
            log.error("捕获到 ClientException，这意味着客户端在尝试与 OSS 通信时遇到了严重问题，例如无法访问网络。");
            log.error("错误信息: {}", ce.getMessage());
        } finally {
            ossClient.shutdown(); // 关闭 OSS 客户端，释放资源
        }
        return "https://" + bucketName + "." + endpoint + "/" + objectName;
    }
}
